package com.fenqing.leetcode.code.t0_200.t0_100;

import com.fenqing.annotations.Execute;
import com.fenqing.core.Topic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author fenqing
 */
public class Topic056 extends Topic {


    /**
     * 构造器
     *
     * @param input     输入
     */
    public Topic056(String input) {
        super(input);
    }

    @Execute
    public int[][] merge(int[][] intervals) {
        // 排序
        Arrays.sort(intervals, Comparator.comparingInt(v -> v[0]));
        List<int[]> result = new ArrayList<>();
        for (int[] interval : intervals) {
            int min = interval[0], max = interval[1];

            if(result.isEmpty() || result.get(result.size() - 1)[1] < min) {
                result.add(interval);
            } else {
                int[] temp = result.get(result.size() - 1);
                if(temp[1] < max) {
                    temp[1] = max;
                }
            }
        }
        return result.toArray(new int[result.size()][]);
    }

    public static void main(String[] args) {
        String input = "[[1,4],[1,4]]";
        int[][] num = new Topic056(input).run();
        System.out.println("input: " + input);
        System.out.println("output: " + Arrays.deepToString(num));
    }
}
